package com.itheima.stargraph.config;

import com.itheima.stargraph.api.ComfyuiApi;
import com.itheima.stargraph.handler.ComfyuiMessageHandler;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @Author Yjr
 * @Date 2025/6/8 15:33
 */
@Configuration
public class ComfyuiConfig {

    @Bean
    public ComfyuiApi comfyuiApi(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://localhost:8188")
                .addConverterFactory(JacksonConverterFactory.create())
                .client(httpClient)
                .build();
        return retrofit.create(ComfyuiApi.class);

    }


    @Bean
    public WebSocketConnectionManager webSocketConnectionManager(ComfyuiMessageHandler comfyuiMessageHandler){
        WebSocketClient webSocketClient = new StandardWebSocketClient();
        String url = "ws://localhost:8188/ws?clientId=star-graph";
        WebSocketConnectionManager webSocketConnectionManager = new WebSocketConnectionManager(webSocketClient, comfyuiMessageHandler, url);
        webSocketConnectionManager.start();

        return webSocketConnectionManager;
    }
}
